<template>
  <div class="app-container">
    <comprehensive-table :columns="column" :data="data" @getPageSize='getPageSize' @onSubmit="onSubmit"
                         @reset="reset" @selection-change="selectionChange">
      <!-- 表格按顺序排列，先是data部分，然后是文章封面图片，最后是添加删除操作按钮-->
      <template v-slot:btn='scope'>
        <div style="display: flex;justify-content: flex-end">
          <el-button type="primary" @click="add"><i class="el-icon-circle-plus icon"></i> 添加</el-button>
        </div>
      </template>

      <!-- v-slot:列名的名字name  文章封面和内容-->
	  <template v-slot:categoryId='scope'>
		  <text>{{scope.row.categoryName}}</text>
	  </template>
      <template v-slot:images='scope'>
        <img :src="getImage(scope.row.images)" style="width:100%;height: aoto;"/>
      </template>
      <template v-slot:content='scope'>
        <text class="content" v-html="scope.row.content"></text>
        <el-button type="text" @click="isExpand=!isExpand;openDialog(scope.row)">展开</el-button>
      </template>

      <template v-slot:operation="scope">
        <el-button icon="Edit" size="small" type="primary" @click="edit(scope.row)">
          <i class="el-icon-edit icon"></i>
          编辑
        </el-button>
        <el-button icon="Delete" size="small" type="danger" @click="del(scope.row)">
          <i class="el-icon-delete icon"></i>
          删除
        </el-button>
      </template>
    </comprehensive-table>

    <!-- 表格中文章内容点击 展开 按钮 -->
    <el-dialog :visible.sync="isExpand" style="top:30%" title="文章内容">
      <text v-html="selectedRowData.content"></text>
    </el-dialog>

    <!-- 点击添加和编辑弹出的对话框 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="50%">

      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" :size="formSize" class="demo-ruleForm"
               label-width="120px">
        <el-form-item label="文章标题" prop="name">
          <el-input v-model="ruleForm.name"/>
        </el-form-item>
        <el-form-item label="文章类型" prop="categoryId">
		  <el-select v-model="ruleForm.categoryId" placeholder="请选择">
		        <el-option label="新闻咨询" value="1"></el-option>
		        <el-option label="热门话题" value="2"></el-option>
		        <el-option label="回收攻略" value="3"></el-option>
		      </el-select>
        </el-form-item>
        <el-form-item label="发布来源" prop="author">
          <el-input v-model="ruleForm.author"/>
        </el-form-item>
        

        <el-form-item label="文章封面" prop="images">
          <!-- 点击编辑按钮 -->
          <view v-if="isFileUpload==false">
            <img v-model="ruleForm.images" :src="getImage(ruleForm.images)"
                 style="width: 70%;border-radius: 10px;"></img>
            <el-upload :auto-upload='false'
                       action=""
					   :on-change="handleChange"
					   :on-remove="handleRemove"
					   :file-list="fileList"
                       list-type="picture">
              <el-button size="small" type="primary">点击修改</el-button>
            </el-upload>
          </view>

          <el-upload v-if="isFileUpload===true"
                     :auto-upload='false'
                     :file-list="fileList"
                     :headers="{'Authorization':'jdk'}"
                     :on-change="handleChange"
                     :on-remove="handleRemove"
                     action=""
                     drag
                     list-type="picture"
                     style="width: 70%;">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>

        </el-form-item>

        <el-form-item label="文章内容" prop="content">
          <div>
            <vue-editor v-model="ruleForm.content" @image-added="uploadImage"></vue-editor>
          </div>
        </el-form-item>

      </el-form>

      <!-- 对话框下面的取消确定按钮 -->
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="dialogVisible = false">取消</el-button>
					<el-button type="primary" @click="submitUpload()">确定</el-button>
				</span>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import axios from "axios";
// 富文本编辑器
import {VueEditor} from 'vue2-editor'

import findingApi from '../../common/finding/FindingApi'
import ComprehensiveTable from './components/comprehensive.vue'

var dayjs = require('dayjs')

const data = []

const column = [{
  type: 'selection',
  width: 60
},
  /* {
    name: 'id',
    label: 'id',
    width: 110,
  }, */
  {
    name: 'name',
    label: '标题',
    //inSearch为true 会出现在最上面
    inSearch: true,
    // 有查询搜索框
    valueType: 'input',
    width: 150
  },
  {
    name: 'categoryId',
    label: '文章类型',
    inSearch: true,
	slot:true,
    options: [{
      value: 1,
      label: '新闻咨询'
    }, {
      value: 2,
      label: '热门话题'
    }, {
      value: 3,
      label: '回收攻略'
    }],
    valueType: 'select',

  },
  {
    name: 'author',
    label: '发布来源',
    inSearch: true,
    valueType: 'input',
  },
  {
    name: 'createTime',
    label: '发布时间',

  },
  {
    name: 'modifyTime',
    label: '上次修改时间',
  },
  {
    name: 'visitors',
    label: '访问量',
  },

  // 文章内容
  {
    name: 'images',
    label: '文章封面',
    slot: true,

  },
  {
    name: 'content',
    label: '文章内容',
    width: 300,
    slot: true,
  },


  {
    name: 'operation',
    label: '操作',
    slot: true,
    fixed: 'right',
    width: 200
  }
]


export default {
  components: {
    ComprehensiveTable,
    VueEditor,

  },

  data() {
    return {
      fileList: [],
      data,
      column,
      formSize: 'default',
      dialogVisible: false,
      title: '新增',
      rowObj: {},
      selectObj: [],
      ruleForm: {
        name: '',
		categoryId:null,
        categoryName: null,
        author: '',
        images: '',
        content: '',
		createTime:'',
		modifyTime:'',//dayjs().format('YYYY-MM-DDTHH:mm:ss[Z]')

		
		id:'',
		visitors:0,
		likes:'',
		video:''
      },
      rules: {
        name: [{
          required: true,
          message: '请输入文章标题',
          trigger: 'blur'
        }],
        images: [{
          required: true,
          message: '请上传文章封面',
          trigger: 'blur'
        }],
        content: [{
          required: true,
          message: '请输入文章内容',
          trigger: 'blur'
        }],


      },
      pageSize: '10',
      isExpand: false,
      selectedRowData: '', //被选中行的数据
      isFileUpload: true, //是否上传文件
    }
  },
  mounted() {
    // 加载文章表格
    this.listArticles()
  },
  methods: {
    handleChange(file, fileList) {
      this.fileList = fileList;
      console.log('图片改变',fileList)
    },
  
    handleRemove(file, fileList) {
      const index = this.fileList.indexOf(file);
      if (index !== -1) {
        this.fileList.splice(index, 1);
      }
    },
	
	// 上传图片
   submitUpload() {
	   // this.fileList.length==0没有修改图片或上传图片
	   if(this.fileList.length==0){
		   this.handleClose('ruleFormRef')
	   }
	   else{
		   // 向后端发送上传请求
      // 在这个方法中，将选择的文件列表放入名为files的集合中，以便发送给后端
      const formData = new FormData();
      this.fileList.forEach(file => {
        formData.append('files', file.raw);
      });

      // 发送上传请求
      axios.post("http://43.136.172.73/api/v1/system/upload/files", formData).then(res => {
        // 处理返回的数据
        if (res.data.code === 200) {
          const imagesUrlList = res.data.data[0];
		  this.ruleForm.images=imagesUrlList
          console.log('上传图片图片路径',imagesUrlList);
		  // 自检表单ruleFormRef
		  this.handleClose('ruleFormRef')
		  
          // 清空fileList
          this.fileList = [];

        } else {
          console.error(res.data.message);
        }
      });
	   }
      
    },


    // 对话框的确认按钮
    async handleClose(formName) {
      // 对整个表单进行自检，返回回调函数。自检正确valid为true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (valid) {
            // 文章对象
            let obj = {
              // id:Date.now(),
              // 使用了对象展开操作符 ...，将 this.ruleForm 对象中手动输入的所有属性和值复制到 obj 中
              ...this.ruleForm,
            }
            // 添加文章对话框
            if (this.title === '新增') {
              // 将一个对象 obj 添加到数组 this.data 的前面，在开头添加
			  this.data = [obj, ...this.data]
              /**发添加请求*/
              findingApi.articleAdd(obj).then(res => {
                console.log('添加成功', res)
                this.$message.success('添加成功')
				this.listArticles()
              })
            }

            // 编辑文章对话框
            else {
              //使用 forEach 方法遍历数组 this.data 中的每个元素，然后检查每个元素的 id 是否与 this.rowObj.id 相匹配。如果找到匹配的元素，它会更新该元素的属性，将其值从 obj 对象中获取。
              this.data.forEach(item => {
                if (item.id === this.rowObj.id) {
                  item.name = obj.name
                  item.categoryName = obj.categoryName
				  item.categoryId = obj.categoryId
                  item.author = obj.author
				  item.images = obj.images
                  item.content = obj.content

                  /** 发更新请求*/
                 let params={
                 	visitors: item.visitors,
                 	categoryId: item.categoryId,
                 	likes:item.likes ,
                	id: item.id,
                	content:item.content ,
                 	video: item.video,
                 	author: item.author,
                 	images: item.images,
                 	name: item.name
                 }
                 // console.log('params',obj,params)
                 findingApi.updateArticle(params).then(res=>{
                 	console.log('更新成功',res)
					this.listArticles()
                })
				}
              })

            }
            this.dialogVisible = false
            console.log('submit!', obj,obj.createTime)
          } else {
            console.log('error submit!', fields)
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 动态获取图片
    getImage(image) {
      return `http://43.136.172.73/api/v1/file/download?fileName=${image}`
    },
    // 点击展开按钮打开对话框
    openDialog(row) {
      this.selectedRowData = row; // 存储被选中行的数据
    },
    listArticles() {
      let params = {
        currentPage: 1,
        // pageSize: this.pageSize
		pageSize:9999
      }
      findingApi.queryFindingArticleList(params).then(res => {
        // console.log('后台查询全部文章内容', res.data.data.records);
        this.data = res.data.data.records
        for (var i = 0; i < this.data.length; i++) {
          // console.log(this.data[i].createTime)
          this.data[i].createTime = this.data[i].createTime.split('T')[0]
          this.data[i].modifyTime = this.data[i].modifyTime.split('T')[0]
          // console.log(this.data[i].createTime)
		 
		 
        }

      })
    },
    // 新增文章
    add() {
      this.title = '新增'
      this.dialogVisible = true
      this.isFileUpload = true
      // 点击编辑后再点添加，不会传值过去
      this.ruleForm.name = ''
      this.ruleForm.author = ''
      this.ruleForm.content = ''


    },

    selectionChange(val) {
      this.selectObj = val
    },

    edit(row) {
      this.title = '编辑'
      this.rowObj = row
	  console.log('row',row)
      this.dialogVisible = true
      this.ruleForm.name = row.name
      this.ruleForm.categoryName = row.categoryName,
	  this.ruleForm.categoryId = row.categoryId,
      this.ruleForm.author = row.author
      this.ruleForm.images = row.images
      this.ruleForm.content = row.content
      this.isFileUpload = false
    },
    // 编辑后面的删除按钮（一次只能删除一个记录）
    del(row) {
      this.$confirm(
          '你确定要删除当前项吗?',
          '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true,
          }
      )
          .then(() => {
            // filter()用于把数组的某些元素的筛选，然后返回剩下的元素。filter()也接收一个数组
            //它会检查数组中的每个元素。对于每个元素 item, 它将检查 item 的 id 属性是否不等于 row 的 id 属性。如果条件成立（true），则元素将包含在新数组中，否则将被过滤掉。
            this.data = this.data.filter(item => item.id !== row.id)
            let params = [row.id]
            findingApi.removeArticle(params).then(res => {
              console.log('删除成功', res)
              this.$message.success('删除成功')
            })
          })
          .catch(() => {
            this.$message.success('删除失败')
          })
    },

    reset() {
      // this.$message.success('触发重置方法')
    },
    /**模糊查询*/
    onSubmit(e) {
		console.log('e',e)
      let params = {
        title: e.name,
        typeId: e.categoryId,
        source: e.author,
        pageSize: this.pageSize,
        currentPage: 1
      }
      findingApi.fuzzyQuery(params).then(res => {
        console.log('聚合模糊查询：', res)
        this.data = res.data.data.records
        for (var i = 0; i < this.data.length; i++) {
          this.data[i].createTime = this.data[i].createTime.split('T')[0]
          this.data[i].modifyTime = this.data[i].modifyTime.split('T')[0]
        }
      })
    },
    getPageSize(pageSize) {
      this.pageSize = pageSize
      console.log('获取到子组件传参-页面大小：', pageSize)
      // 点击每页显示多少条数据后再显示
      this.listArticles()
    }

  }
}
</script>
<style scoped>
.edit-input {
  padding-right: 100px;
}

.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}

.icon {
  margin-right: 4px;
}


.content {
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}
</style>